package moonlit.chill.pay.service.impl.wechat;

import cn.hutool.core.util.ObjectUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.http.AbstractHttpClient;
import com.wechat.pay.java.core.http.DefaultHttpClientBuilder;
import com.wechat.pay.java.core.util.IOUtil;
import com.wechat.pay.java.service.billdownload.BillDownloadService;
import com.wechat.pay.java.service.billdownload.model.GetTradeBillRequest;
import com.wechat.pay.java.service.billdownload.model.QueryBillEntity;
import lombok.extern.slf4j.Slf4j;
import moonlit.chill.pay.cache.PayConfigDataCache;
import moonlit.chill.pay.constants.Constants;
import moonlit.chill.pay.service.PayStrategy;
import moonlit.chill.pay.util.WxConfigUtil;
import moonlit.chill.pay.vo.PayConfig;
import moonlit.chill.pay.vo.PayResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MoonlitChill
 * @date 2024/4/15 16:00
 */
@Slf4j
@Service("wxBillStrategy")
public class WxBillStrategyServiceImpl implements PayStrategy {

    @Resource
    private PayConfigDataCache payConfigDataCache;

    @Autowired
    private WxConfigUtil wxConfigUtil;

    @Override
    public PayResult<List<String[]>> payForBill(String date) {
        PayResult<List<String[]>> result = new PayResult<>();
        InputStream inputStream = null;
        try {
            PayConfig payConfig = payConfigDataCache.getPayConfig();
            Config config = wxConfigUtil.getConfig(payConfig);
            BillDownloadService service = new BillDownloadService.Builder().config(config).build();
            GetTradeBillRequest billRequest = new GetTradeBillRequest();
            billRequest.setBillDate(date);
//        billRequest.setTarType(TarType.GZIP);
            QueryBillEntity tradeBill = service.getTradeBill(billRequest);
            if (ObjectUtil.isNotEmpty(tradeBill)) {
                String downloadUrl = tradeBill.getDownloadUrl();
                DefaultHttpClientBuilder builder = new DefaultHttpClientBuilder();
                AbstractHttpClient build = builder.config(config).build();
                inputStream = build.download(downloadUrl);
                //下载账单为GZIP文件
//                File file = new File(payConfig.getDownPath() + payConfig.getUId() + payForBill.getDate() + ".gzip");
//                FileUtils.copyInputStreamToFile(inputStream, file);
                String respBody = IOUtil.toString(inputStream);
                String[] split = respBody.split("\n");
                List<String[]> list = new ArrayList<>();
                for (int i = 1; i < split.length - 2; i++) {
                    String s = split[i];
                    s = s.substring(1);
                    String[] strings = s.split(",`");
                    list.add(strings);
                }
                result.setSuccess(Boolean.TRUE);
                result.setResult(list);
            } else {
                result.error("下载微信账单异常", Constants.PAY_FAIL_CODE);
            }
        } catch (Exception e) {
            result.errorWithException(e.getMessage(), Constants.PAY_FAIL_CODE, e);
        } finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("下载微信账单IO关闭异常", e);
                    result.errorWithException(e.getMessage(), Constants.PAY_FAIL_CODE, e);
                }
            }
        }
        return result;
    }
}
